package com.kehao.leetcode.basic.tree;


public class TreeSolution2 {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean isValidBST(TreeNode root) {
        if(root==null){
            return true;
        }
        boolean isLeftBst = isValidBST(root.left);
        boolean isRightBst = isValidBST(root.right);
        if(root.left!=null){
            int leftMax = getLeftMax(root);
            if(leftMax>=root.val||!isLeftBst){
                return false;
            }
        }
        if(root.right!=null){
            int rightMin = getRightMin(root);
            if(rightMin<=root.val||!isRightBst){
                return false;
            }
        }
        return true;
    }

    public int getLeftMax(TreeNode root){
        root = root.left;
        while (root.right!=null){
            root=root.right;
        }
        return root.val;
    }

    public int getRightMin(TreeNode root){
        root = root.right;
        while (root.left!=null){
            root = root.left;
        }
        return root.val;
    }

}
